const { Router } = require('express')
const router = new Router()

// 引入分类模型（classification）
const ClassificationModel = require('../../../model/classification')

const path = require('path')

// 引入删除文件函数
const removeFile = require('../../../utils/fileUtils/removeFile')
const moveFile = require('../../../utils/fileUtils/moveFile')
// 引入url
const url = require('../../../config/url')
const regUrl = url.substr(0, url.length - 1)

// 引入验证角色权限
const rolesPermission = require('../../../utils/validateRole/rolesPermission')

router.get('/updateClassification',function (request, response) {
    const checkResult = checkPermit(request)
    if (!checkResult.isSuccess) return response.json(checkResult.data)

    const { _id, typeName, typePic, typeArr, isShow } = request.query

    const data = {
        code: '200',
        data: 'error',
        msg: '修改分类失败'
    }

    // 变更这个方法是想自动删除文件，不想搞太多文件垃圾在自己的项目里面
    ClassificationModel.findOne({
        _id
    }, (err,doc) => {
        if (err) return response.json(data)

        const reg = new RegExp(regUrl,'g')
        const filePath = doc.typePic.replace(reg, path.resolve(__dirname,'../../../'))

        removeFile(filePath, status => {

            if (status.isSuccess){
                // 需要移动的文件名
                const fileName = path.parse(typePic).base
                //  需要移动到的文件夹路径
                const newPath = path.resolve(__dirname,'../../../public/free/classification',fileName)
                // 临时存储的路径
                const oldPath = path.resolve(__dirname, '../../../public/free/temp', fileName)

                moveFile(newPath,oldPath, status2 => {
                    if (status2.isSuccess){
                        ClassificationModel.updateOne({
                            _id
                        },{
                            typeName,
                            typePic: `${url}public/free/classification/${fileName}`,
                            typeArr,
                            isShow
                        },(err,doc) => {

                            if (err) return response.json(data);

                            data.data = 'success'
                            data.msg = '修改分类成功'

                            response.json(data)
                        })

                    }else {
                        response.json(data)
                    }
                })


            } else {
                response.json(data)
            }
        })

    })

})

router.get('/deleteClassfication', function (request, response) {
    const checkResult = checkPermit(request)
    if (!checkResult.isSuccess) return response.json(checkResult.data)

    const { _id } = request.query

    const data = {
        code: '200',
        data: 'error',
        msg: '删除分类失败'
    }

    // 变更这个方法是想自动删除文件，不想搞太多文件垃圾在自己的项目里面
    ClassificationModel.findOne({
        _id
    }, (err,doc) => {
        if (err) return response.json(data)

        const reg = new RegExp(regUrl,'g')
        const filePath = doc.typePic.replace(reg, path.resolve(__dirname,'../../../'))

        removeFile(filePath, status => {
            if (status.isSuccess){
                ClassificationModel.deleteOne({
                    _id
                },function (err,doc) {
                    if (err) return response.json(data);

                    data.data = 'success'
                    data.msg = '删除分类成功'

                    response.json(data)
                })
            } else {
                response.json(data)
            }
        })

    })
})

function checkPermit(request){
    const validate = {
        permitRoles: ['admin'],
        secret: request.get('permission')
    }

    const data = {
        code: '200',
        data: 'error',
        msg: '权限不足'
    }
    if (!rolesPermission(validate)) return {
        isSuccess: false,
        data
    };

    return {
        isSuccess: true
    }
}

module.exports = router
